package org.vectrics.recruiter.struts.admin;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Category;
import org.apache.struts.action.ActionForm;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.system.SystemConstant;
import org.vectrics.user.Person;



public class SaveConfigurationAction extends VectricsStrutsAction {
	public static final long serialVersionUID = 3466434642223L;
    private static Category log = Category.getInstance(SaveConfigurationAction.class);
	
    public SaveConfigurationAction() {
    	super();
    }


	public String doExecute(VectricsActionData actionData)	throws JspException {
		Request request = actionData.getRequest();
		ActionForm form = actionData.getForm();
		ConfigurationForm configForm = (ConfigurationForm)form;
		String forwardCode = "success";

		if (actionData.wasButtonPressed("cancel") == false) {
			ThreadProperties.getSession().clear();

			Person authPerson = CoreServiceLocator.getUserAuthService().getAuthorizedPerson(ThreadProperties.getDomain(), request);
		
			Domain domain = CoreServiceLocator.getSystemService().findDomain(new Long(configForm.getDomainId()));
			saveConstant(domain, "resume.recipient.email.addr", configForm.getResumeEmailAddress());
			saveConstant(domain, "resume.recipient.email.host", configForm.getResumeEmailHost());
			saveConstant(domain, "resume.recipient.email.password", configForm.getResumeEmailPassword());
		} else {
		    log.debug("Cancel button pressed.");
		    forwardCode = "cancel";
		}
		ThreadProperties.forcedCommit();
		return (forwardCode);
    }
	
    private void saveConstant(Domain domain, String code, String newValue) {
    	log.info("saveConstant() - saving value for: " + code);
    	SystemConstant systemConstant = CoreServiceLocator.getSystemService().findSystemConstant(domain, code);
    	systemConstant.setValue(newValue);
    	CoreServiceLocator.getSystemService().updateSystemConstant(systemConstant);
    }
}
